package com.impress;

import java.net.SocketTimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.conn.ConnectTimeoutException;

import com.impress.R;
import com.impress.Utility.BadAccountException;
import com.impress.model.AccountPreference;
import com.mobclick.android.MobclickAgent;
import com.mobclick.android.ReportPolicy;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
//import android.content.ContextWrapper;
//import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class AccountLogin extends Activity {

	private static final String TAG = "AccountLoginActivity";
	
	private static final int LOGIN_BEGIN = 0;
	private static final int LOGIN_FINISH = 1;
	private static final int LOGIN_FAILED = 2;
	
	private EditText tb_email;
	private EditText tb_password;
	private Button b_login;
	
	private TitleBar mTitle;
	private View progressBar;
	private String mEmail;
	private String mPassword;
	
	private final Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LOGIN_BEGIN:
				b_login.setEnabled(false);
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
				progressBar.setVisibility(View.VISIBLE);
				break;
			case LOGIN_FAILED:
				b_login.setEnabled(true);
				progressBar.setVisibility(View.GONE);
				if (msg.arg1 != 0) {					
					Toast.makeText(AccountLogin.this, getString(msg.arg1), Toast.LENGTH_LONG).show();
				}
				break;
			case LOGIN_FINISH:
				AccountLogin.this.finish();
				Intent i = new Intent(AccountLogin.this,MainListActivity.class);
				startActivity(i);
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		MobclickAgent.onError(this);
		MobclickAgent.setReportPolicy(ReportPolicy.DAILY);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login);
		
		AccountPreference settings = new AccountPreference(this);
		String tempEmail = settings.getAccount().get_email();
		String tempPassword = settings.getAccount().get_password();
		
		mTitle = (TitleBar)findViewById(R.id.titlebar);
		tb_email = (EditText)findViewById(R.id.email);
		tb_password = (EditText)findViewById(R.id.password);
		b_login = (Button)findViewById(R.id.b_login);
		progressBar = (LinearLayout)findViewById(R.id.progress);
		
		mTitle.clearView();
		tb_email.setText(tempEmail);
		tb_password.setText(tempPassword);
		b_login.setEnabled(TextFieldIsNull(tempEmail,tempPassword));
		TextWatcher watcher = new TextWatcher(){

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				b_login.setEnabled(TextFieldIsNull(tb_email.getText().toString().trim(),
						tb_password.getText().toString().trim()));
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				
			}
			
		};		
				
		tb_email.addTextChangedListener(watcher);
		tb_password.addTextChangedListener(watcher);
		b_login.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				mEmail = tb_email.getText().toString().trim();
				mPassword = tb_password.getText().toString().trim();

				if(mEmail.indexOf('@')<0){
					mEmail += "@gmail.com";
					tb_email.setText(mEmail);
				}
				if(TextFieldIsNull(mEmail,mPassword) && CheckEmail(mEmail)){
					new Thread() {
						
						@Override
						public void run() {
							Message message = new Message();
							message.what = LOGIN_BEGIN;
							handler.sendMessage(message);
							Login(mEmail, mPassword);
							
						}
					}.start();
				}
			}
			
		});
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	/**
	 * 使用文本框中的邮件以及密码登录
	 * @param email
	 * @param password
	 */
	public void Login(String email, String password){
		GoogleAccount account = new GoogleAccount();
		account.set_email(email);
		account.set_password(password);
		Boolean isSuccess = false;
		int errorMessage = R.string.accountInfoUnavailableString;
		Message message = new Message();
		try {
			isSuccess = account.Login();
			if(isSuccess){
				SaveAccount(account);
				message.what = LOGIN_FINISH;
				handler.sendMessage(message);				
			}
			return;
		}
		catch (BadAccountException e) {
			errorMessage = R.string.badAccountInfoString;
		}
		catch (ConnectTimeoutException e) {
			errorMessage = R.string.connectionFailedString;
		}
		catch (SocketTimeoutException e) {
			errorMessage = R.string.noRespondString;
		}
		catch (Exception e) {
		}
		message.what = LOGIN_FAILED;
		message.arg1 = errorMessage;
		handler.sendMessage(message);
	}
	
	/**
	 * 检查email格式是否正确
	 * @param email
	 * @return
	 */
	public Boolean CheckEmail(String email){
		Boolean result = true;
		final String reg = 
			"^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		final Pattern pattern = Pattern.compile(reg);
		final Matcher mat = pattern.matcher(email);
		if(!mat.find()){
			result = false;
		}
		return result;
	}
	
	/**
	 * 检查是否存在字串为空
	 * @param str1
	 * @param str2
	 * @return 若有一个为空，则返回false,两者都不为空，则返回true
	 */
	public Boolean TextFieldIsNull(String str1, String str2){

		return (!TextUtils.isEmpty(str1)) && 
			(!TextUtils.isEmpty(str2));
	}
	
	/**
	 * 保存账户信息
	 * @param account GoogleAccount对象
	 */
	private void SaveAccount(GoogleAccount account){
		AccountPreference settings = new AccountPreference(this);
		settings.setAccount(account);
		settings.SaveUser();		
	}

}
